<template>
  <div id="fill-insurance-policy" :class="{'pb-0': type === 'part'}">

    <grey-header title="商业险保单生效时间" class="tips"></grey-header>

    <ul>
      <li class="public-form-li">
        <label class="long">是否即时生效</label>
        <label for="effectNow">是
          <input
            type="radio"
            name="effectNow"
            id="effectNow"
            value="1"
            :disabled="allDisabled"
            v-model="formTwo.effectTiming">
        </label>
        <label for="effectLater">否
          <input
            type="radio"
            name="effectLater"
            id="effectLater"
            value="2"
            :disabled="allDisabled"
            v-model="formTwo.effectTiming">
        </label>
      </li>
      <template v-if="formTwo.effectTiming === '1'">
        <li class="public-form-li li-click">
          <label class="short" for="insuranceEffectDate">生效日期</label>
          <input
            class="disabled"
            disabled
            type="button"
            id="insuranceEffectDate"
            :value="insuranceEffectDate">
        </li>
        <li class="public-form-li li-others">
          <label class="short" for="advancedInsuranceEffectTime">生效时间</label>
          <section class="others">
            提前&nbsp;&nbsp;
            <select
              v-model="formTwo.advancedInsuranceEffectTime"
              name="advancedInsuranceEffectTime"
              id="advancedInsuranceEffectTime"
              :disabled="allDisabled">
              <option v-for="(item, index) in advancedHours" :key="index">{{ index }}</option>
            </select>
            &nbsp;&nbsp;小时生效
          </section>
        </li>
      </template>
      <template v-if="formTwo.effectTiming === '2'">
        <li class="public-form-li li-click">
          <label for="customInsuranceEffectDate" class="short">生效日期</label>
          <input
            type="button"
            id="customInsuranceEffectDate"
            :value="customInsuranceEffectDate"
            @click="openDatetimePicker('datetimePicker')"
            :disabled="allDisabled">
          <button
            class="date-btn"
            @click="openDatetimePicker('datetimePicker')"
            :disabled="allDisabled"></button>
        </li>
      </template>
      <li class="public-form-li message note" v-if="formTwo.effectTiming === '1'">
        注：生效时间为当天24:00
      </li>
      <li class="public-form-li message note" v-if="formTwo.effectTiming === '2'">
        注：生效时间为当天00:00
      </li>
    </ul>

    <grey-header title="交强险保单生效时间" class="tips"></grey-header>

    <ul>
      <li class="public-form-li">
        <label class="long">是否即时生效</label>
        <label for="jqEffectNow">是
          <input
            type="radio"
            name="jqEffectNow"
            id="jqEffectNow"
            value="1"
            :disabled="allDisabled"
            v-model="formTwo.jqEffectTiming">
        </label>
        <label for="jqEffectLater">否
          <input
            type="radio"
            name="jqEffectLater"
            id="jqEffectLater"
            value="2"
            :disabled="allDisabled"
            v-model="formTwo.jqEffectTiming">
        </label>
      </li>
      <template v-if="formTwo.jqEffectTiming === '1'">
        <li class="public-form-li li-click">
          <label class="short" for="jqInsuranceEffectDate">生效日期</label>
          <input
            class="disabled"
            disabled
            type="button"
            id="jqInsuranceEffectDate"
            :value="jqInsuranceEffectDate">
        </li>
        <li class="public-form-li li-others">
          <label class="short" for="jqAdvancedInsuranceEffectTime">生效时间</label>
          <section class="others">
            提前&nbsp;&nbsp;
            <select
              v-model="formTwo.jqAdvancedInsuranceEffectTime"
              name="jqAdvancedInsuranceEffectTime"
              id="jqAdvancedInsuranceEffectTime"
              :disabled="allDisabled">
              <option v-for="(item, index) in advancedHours" :key="index">{{ index }}</option>
            </select>
            &nbsp;&nbsp;小时生效
          </section>
        </li>
      </template>
      <template v-if="formTwo.jqEffectTiming === '2'">
        <li class="public-form-li li-click">
          <label for="jqCustomInsuranceEffectDate" class="short">生效日期</label>
          <input
            type="button"
            id="jqCustomInsuranceEffectDate"
            :value="jqCustomInsuranceEffectDate"
            @click="openDatetimePicker('jqDatetimePicker')"
            :disabled="allDisabled">
          <button
            class="date-btn"
            @click="openDatetimePicker('jqDatetimePicker')"
            :disabled="allDisabled"></button>
        </li>
      </template>
      <li class="public-form-li message note" v-if="formTwo.jqEffectTiming === '1'">
        注：生效时间为当天24:00
      </li>
      <li class="public-form-li message note" v-if="formTwo.jqEffectTiming === '2'">
        注：生效时间为当天00:00
      </li>
    </ul>

    <grey-header title="保单信息"></grey-header>

    <ul>
      <li class="public-form-li li-single-checkbox">
        <label class="long">需要保单凭证</label>
        <label for="needEvidence">
          <input
            type="checkbox"
            id="needEvidence"
            true-value="1"
            false-value="2"
            v-model="formOne.needEvidence">
        </label>
      </li>
      <template v-if="formOne.needEvidence === '1'">
        <li class="public-form-li li-single-checkbox">
          <label class="short">获取方式</label>
          <label for="byMail">邮寄
            <input
              disabled
              type="checkbox"
              id="byMail"
              true-value="1"
              v-model="formOne.byMail">
          </label>
        </li>
        <li class="public-form-li">
          <label class="short" for="receiverName">收件人姓名</label>
          <input
            type="text"
            placeholder="请输入收件人姓名"
            id="receiverName"
            name="收件人姓名"
            v-model="formOne.receiverName"
            v-validate="'userName'">
          <span v-show="VeeErrors.has('收件人姓名')">{{ VeeErrors.first('收件人姓名') }}</span>
        </li>
        <li class="public-form-li">
          <label class="short" for="receiverTel">收件人电话</label>
          <input
            type="text"
            placeholder="请输入收件人电话"
            id="receiverTel"
            name="收件人电话"
            v-model="formOne.receiverTel"
            v-validate="'tel'">
          <span v-show="VeeErrors.has('收件人电话')">{{ VeeErrors.first('收件人电话') }}</span>
        </li>
        <li class="public-form-li li-click">
          <label class="long" for="receiverLocation">填写邮寄地址</label>
          <input
            type="button"
            id="receiverLocation"
            :value="receiverLocation"
            @click="formOne.aboutPlace.placeShow = true">
          <button
            class="address-btn"
            @click="formOne.aboutPlace.placeShow = true"
            :disabled="allDisabled"></button>
        </li>
        <li class="public-form-li">
          <label class="short" for="receiverBlocks"></label>
          <input
            type="text"
            placeholder="请输入详细街道,如:中山路20号"
            id="receiverBlocks"
            name="详细地址"
            v-model="formOne.aboutPlace.blocks">
        </li>
      </template>
    </ul>

    <footer class="public-footer-btn-box" v-if="type === 'page'">
      <button
        @click="submit"
        :disabled="submitDisabled"
        class="single-button">提交</button>
    </footer>

    <popup
      v-model="formOne.aboutPlace.placeShow"
      position="bottom"
      class="placesPopup">
      <picker
        :slots="formOne.aboutPlace.places"
        value-key="name"
        @change="pickedPlaceChange"></picker>
    </popup>

    <datetime-picker
      type="date"
      :startDate="new Date(new Date().getTime() + 24*3600*1000)"
      :endDate="new Date(new Date().getTime() + 90*24*3600*1000)"
      v-model="date"
      @confirm="confirmDate"
      @cancel="pickPopupChange(false)"
      ref="datetimePicker">
    </datetime-picker>

    <datetime-picker
      type="date"
      :startDate="new Date(new Date().getTime() + 24*3600*1000)"
      :endDate="new Date(new Date().getTime() + 90*24*3600*1000)"
      v-model="jqDate"
      @confirm="confirmJqDate"
      @cancel="pickPopupChange(false)"
      ref="jqDatetimePicker">
    </datetime-picker>
  </div>
</template>

<script>
  import { Popup, Picker, DatetimePicker } from 'mint-ui';
  import GreyHeader from './grey-header.vue';
  export default {
    name: "fill-insurance-policy",
    components: {
      Popup,
      Picker,
      GreyHeader,
      DatetimePicker
    },
    props: ['type', 'info', 'editable'],
    data() {
      return {
        formOne: {
          needEvidence: '1',
          byMail: '1',
          receiverName: '',
          receiverTel: '',
          aboutPlace: {
            placeShow: false,

            // 数据

            province: '',
            city: '',
            district: '',
            blocks: '',

            // 汇总

            // 一个省的所有城市（一个城市为一个{}）为一个数组
            citiesArr: [
              [
                {
                  name: '请选择',
                  areas: [],
                  cityIndex: 0
                }
              ]
            ],
            // 一个市的所有区域为一个数组
            areasArr: [
              [
                {
                  name: '请选择'
                }
              ]
            ],

            // picker数据格式

            places: [
              {
                flex: 1,
                values: [
                  {
                    name: '请选择',
                    index: 0
                  }
                ],
                textAlign: 'center'
              },
              {
                flex: 1,

                // 结构参考 citiesArr 的 item

                values: [
                  {
                    name: '请选择',
                    cityIndex: 0,
                    areas: []
                  }
                ],
                textAlign: 'center'
              },
              {
                flex: 1,

                // 结构参考 areasArr 的 item

                values: [
                  {
                    name: '请选择'
                  }
                ],
                textAlign: 'center'
              }
            ]
          }
        },
        formTwo: {
          effectTiming: '2',
          advancedInsuranceEffectTime: '0',
          jqEffectTiming: '2',
          jqAdvancedInsuranceEffectTime: '0'
        },
        allDisabled: false,
        submitDisabled: false,
        date: '',
        formattedYear: this.$tool.formattedDate(new Date(new Date().getTime() + 3600 * 24 * 1000)).year,
        formattedMonth: this.$tool.formattedDate(new Date(new Date().getTime() + 3600 * 24 * 1000)).month,
        formattedDay: this.$tool.formattedDate(new Date(new Date().getTime() + 3600 * 24 * 1000)).day,

        jqDate: '',
        jqFormattedYear: this.$tool.formattedDate(new Date(new Date().getTime() + 3600 * 24 * 1000)).year,
        jqFormattedMonth: this.$tool.formattedDate(new Date(new Date().getTime() + 3600 * 24 * 1000)).month,
        jqFormattedDay: this.$tool.formattedDate(new Date(new Date().getTime() + 3600 * 24 * 1000)).day
      }
    },
    computed: {
      receiverLocation: {
        get() {
          return this.formOne.aboutPlace.province + '-'
            + this.formOne.aboutPlace.city + '-'
            + this.formOne.aboutPlace.district
        },
        set(newValue) {

          if (!newValue) {
            this.formOne.aboutPlace.province = '请选择';
            this.formOne.aboutPlace.city = '请选择';
            this.formOne.aboutPlace.district = '请选择';

            this.formOne.aboutPlace.blocks = '';
          } else {

            // 'xx省-xx市-xx区 xx路'

            let addressStrings = newValue.toString().split(' ');
            let strings = addressStrings[0].toString().split('-');
            this.formOne.aboutPlace.province = strings[0] || '请选择';
            this.formOne.aboutPlace.city = strings[1] || '请选择';
            this.formOne.aboutPlace.district = strings[2] || '请选择';

            this.formOne.aboutPlace.blocks = addressStrings[1];
          }
        }
      },
      receiverAddress() {
        return (this.receiverLocation === '请选择-请选择-请选择' ? '' : this.receiverLocation) + ' '
          + this.formOne.aboutPlace.blocks
      },
      insuranceEffectDate() {
        let date = new Date();
        return this.$tool.formattedDate(date).year + '-'
          + this.$tool.formattedDate(date).month + '-'
          + this.$tool.formattedDate(date).day;
      },
      jqInsuranceEffectDate() {
        let date = new Date();
        return this.$tool.formattedDate(date).year + '-'
          + this.$tool.formattedDate(date).month + '-'
          + this.$tool.formattedDate(date).day;
      },
      advancedHours() {
        let date = new Date();
        return 24 - date.getHours();
      },
      customInsuranceEffectDate: {
        get() {
          return this.formattedYear + '-' + this.formattedMonth + '-' + this.formattedDay;
        },
        set(newValue) {
          let strings = newValue.toString().split('-');
          this.formattedYear = strings[0];
          this.formattedMonth = strings[1];
          this.formattedDay = strings[2];
        }
      },
      jqCustomInsuranceEffectDate: {
        get() {
          return this.jqFormattedYear + '-' + this.jqFormattedMonth + '-' + this.jqFormattedDay;
        },
        set(newValue) {
          let strings = newValue.toString().split('-');
          this.jqFormattedYear = strings[0];
          this.jqFormattedMonth = strings[1];
          this.jqFormattedDay = strings[2];
        }
      }
    },
    methods: {
      pickPopupChange(newVal) {
        this.$tool.fixedTheBG(newVal, 'fill-insurance-policy');
      },
      pickedPlaceChange(picker, values) {

        // 1.1 根据省份获取城市列表（城市列表中包含 areas 数组）

        picker.setSlotValues(1, this.formOne.aboutPlace.citiesArr[values[0].index]);

        // 1.2 赋值省份

        this.formOne.aboutPlace.province = values[0].name;

        // 2.1 根据城市获取区域列表

        picker.setSlotValues(2, this.formOne.aboutPlace.areasArr[values[1].cityIndex]);

        // 2.2 赋值城市

        this.formOne.aboutPlace.city = values[1].name;

        // 3. 赋值区域

        this.formOne.aboutPlace.district = values[2].name;
      },
      submit() {
        this.$validator.validateAll().then((result) => {

          // 验证通过

          if (result) {

            if (this.formTwo.effectTiming === '2' && this.customInsuranceEffectDate === '请选择-请选择-请选择') {
              alert('请选择保单生效日期。');
            } else {
              this.$http.post({
                api: this.$api.INSURANCE_POLICY_INFO,
                params: {
                  car_owner_id: this.$route.params.car_owner_id,
                  car_id: this.$route.params.car_id,
                  user_id: localStorage.getItem('id'),

                  /**
                   * 表单一
                   */
                  is_get: this.formOne.needEvidence,
                  mail: this.formOne.byMail,
                  name: this.formOne.receiverName,
                  phone: this.formOne.receiverTel,
                  address: this.receiverAddress,

                  /**
                   * 表单二
                   */
                  is_immefc: this.formTwo.effectTiming,
                  start_time: this.formTwo.effectTiming === '1' ?
                    this.insuranceEffectDate + ' ' + (23 - this.formTwo.advancedInsuranceEffectTime) + ':00:00' :
                    this.customInsuranceEffectDate + ' 00:00:00',
                  hours: this.formTwo.advancedInsuranceEffectTime,

                  jq_is_immefc: this.formTwo.jqEffectTiming,
                  jq_start_time: this.formTwo.jqEffectTiming === '1' ?
                    this.jqInsuranceEffectDate + ' ' + (23 - this.formTwo.jqAdvancedInsuranceEffectTime) + ':00:00' :
                    this.jqCustomInsuranceEffectDate + ' 00:00:00',
                  jq_hours: this.formTwo.jqAdvancedInsuranceEffectTime
                },
                success: (res) => {

                  this.$tool.whenToast(
                    () => {

                      // 提示并禁止重复提交、点击，不再恢复（组件即将销毁）

                      this.submitDisabled = true;
                      this.allDisabled = true;
                    },
                    {
                      message: '提交成功，请继续选择险种',
                      className: 'public-long-toast'
                    },
                    () => {
                      this.$router.push({
                        name: 'FillInsuranceDetail',
                        params: {
                          type: this.$route.params.type,
                          car_owner_id: res.data.data.car_owner_id,
                          car_id: res.data.data.car_id,
                          policy_id: res.data.data.policy_id
                        },
                        query: {
                          last_page: 'policy'
                        }
                      });
                    },2000
                  );
                }
              });
            }

          } else {

            this.$tool.whenToast(
              () => {

                // 禁止重复点击

                this.submitDisabled = true;
              },
              {
                message: '请完善保单信息',
                position: 'center',
                duration: -1,
                iconClass: 'public-toast-icon error'
              },
              () => {

                // 恢复点击

                this.submitDisabled = false;
              },2000
            );
          }
        })
      },
      partInfoApply() {
        let info = this.info;

        this.formOne.needEvidence = info.needEvidence;
        this.formOne.byMail = info.byMail;
        this.formOne.receiverName = info.receiverName;
        this.formOne.receiverTel = info.receiverTel;
        this.receiverLocation = info.receiverAddress;

        this.formTwo.effectTiming = info.effectTiming;

        this.customInsuranceEffectDate = info.insuranceEffectDate.split(' ')[0];

        this.formTwo.advancedInsuranceEffectTime = info.advancedInsuranceEffectTime;

        this.formTwo.jqEffectTiming = info.jqEffectTiming;

        this.jqCustomInsuranceEffectDate = info.jqInsuranceEffectDate.split(' ')[0];

        this.formTwo.jqAdvancedInsuranceEffectTime = info.jqAdvancedInsuranceEffectTime;
      },
      trickUpdateNeedEvidence(newValue, oldValue) {
        this.$emit('updateNeedEvidence', newValue);
      },
      trickUpdateReceiverName(newValue, oldValue) {
        this.$emit('updateReceiverName', newValue);
      },
      trickUpdateReceiverTel(newValue, oldValue) {
        this.$emit('updateReceiverTel', newValue);
      },
      trickUpdateReceiverAddress(newValue, oldValue) {
        this.$emit('updateReceiverAddress', newValue);
      },
      openDatetimePicker(ref) {
        this.$refs[ref].open();
        this.pickPopupChange(true);
        // tag （this.pickPopupChange(false)）
        setTimeout(() => {
          document.getElementsByClassName('v-modal')[0].onclick = function () {
            this.pickPopupChange(false);
          }.bind(this)
        })
      },
      confirmDate(date) {
        this.formattedYear = this.$tool.formattedDate(date).year;
        this.formattedMonth = this.$tool.formattedDate(date).month;
        this.formattedDay = this.$tool.formattedDate(date).day;

        this.pickPopupChange(false);
      },
      confirmJqDate(date) {
        this.jqFormattedYear = this.$tool.formattedDate(date).year;
        this.jqFormattedMonth = this.$tool.formattedDate(date).month;
        this.jqFormattedDay = this.$tool.formattedDate(date).day;

        this.pickPopupChange(false);
      }
    },
    created() {

      // 城市代码

      this.$http.post({
        api: this.$api.INSURANCE_CITY,
        success: (res) => {

          // 初始化时已有 0 项
          let cityIndex = 1,
            data = res.data.data,
            citiesArr = this.formOne.aboutPlace.citiesArr,
            areasArr = this.formOne.aboutPlace.areasArr;

          for (let index = 0; index < data.length; index++) {
            // 获取城市、汇总（城市item中包含 areas 数组）

            citiesArr.push(data[index].cities);

            // 获取区域、汇总（给每个区域赋值城市 cityIndex）（初始化时已有0项）

            for (let subIndex = 0; subIndex < citiesArr[index + 1].length; subIndex++) {
              let eachCity = citiesArr[index + 1][subIndex];
              eachCity.cityIndex = cityIndex;
              areasArr.push(eachCity.areas);
              cityIndex++;
            }

            // 获取省份 并 直接赋值到picker数据格式中

            this.formOne.aboutPlace.places[0].values.push({
              name: data[index].name,
              index: index + 1
            });
          }

          if (this.type === 'part') {
            this.receiverLocation = this.info.storageReceiverAddress;
          }
        }
      });

      // 判断是否可编辑

      if (this.editable) {
        this.allDisabled = false;
      } else if (!this.editable) {
        this.allDisabled = true;
      }

      if (this.type === 'part') {
        this.partInfoApply();
      }
    },
    watch: {
      'formOne.aboutPlace.placeShow': 'pickPopupChange',
      'formOne.needEvidence':'trickUpdateNeedEvidence',
      'formOne.receiverName':'trickUpdateReceiverName',
      'formOne.receiverTel':'trickUpdateReceiverTel',
      'receiverAddress':'trickUpdateReceiverAddress'
    }
  }
</script>

<style lang="scss">


  #fill-insurance-policy {

    width: $size-as-parent;
    padding-bottom: $public-footer-btn-box-height;
    z-index: $content-z-index;

    >ul {
      padding: $public-form-padding;
      background: $white;
    }

    >.placesPopup {
      width: $size-as-parent;
      padding: 1rem 0;
    }
  }
</style>
